'use client'

import { useState, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Progress } from '@/components/ui/progress'
import { Badge } from '@/components/ui/badge'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { 
  IconUpload, 
  IconFileText, 
  IconChevronRight, 
  IconCheck, 
  IconClock,
  IconLoader,
  IconX,
  IconEye,
  IconDownload
} from '@tabler/icons-react'
import { api, type FloorPlan, type SegmentResult, type TaskStatus } from '@/lib/api'
import { toast } from 'sonner'
import AuthGuard from '@/components/AuthGuard'
<<<<<<< HEAD

// 后端服务基础地址
const AI_BASE = process.env.NEXT_PUBLIC_AI_API_BASE_URL || 'http://localhost:8000'
=======
import { AI_BASE_URL } from '@/lib/config'

// 后端服务基础地址
const AI_BASE = AI_BASE_URL
>>>>>>> 2b1414599d9e635ed6f7f739f5d192143c8f58df

interface ProcessingStep {
  id: string
  name: string
  status: 'pending' | 'running' | 'completed' | 'failed'
  icon: React.ReactNode
}

export default function FloorProcessingPage() {
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [uploadedFloor, setUploadedFloor] = useState<FloorPlan | null>(null)
  const [segmentResult, setSegmentResult] = useState<SegmentResult | null>(null)
  const [currentTask, setCurrentTask] = useState<TaskStatus | null>(null)
  const [isUploading, setIsUploading] = useState(false)
  const [isProcessing, setIsProcessing] = useState(false)
  const [glbUrl, setGlbUrl] = useState<string | null>(null)
  const [retryCount, setRetryCount] = useState<Record<string, number>>({})
  const [hybrid3dResult, setHybrid3dResult] = useState<any>(null)
  const [webDemoUrl, setWebDemoUrl] = useState<string | null>(null)

  const [steps, setSteps] = useState<ProcessingStep[]>([
    { id: 'upload', name: '1. 上传平面图', status: 'pending', icon: <IconUpload size={20} /> },
    { id: 'segment', name: '2. AI智能分割', status: 'pending', icon: <IconLoader size={20} /> },
    { id: 'vectorize', name: '3. 矢量化处理', status: 'pending', icon: <IconFileText size={20} /> },
    { id: 'hybrid_3d', name: '4. 混合3D建模', status: 'pending', icon: <IconLoader size={20} /> },
    { id: 'complete', name: '5. 处理完成', status: 'pending', icon: <IconCheck size={20} /> }
  ])
  
  // 建模方法选择
  const [modelingMethod, setModelingMethod] = useState<'hybrid' | 'mcp' | 'traditional'>('hybrid')

  // 文件拖拽处理
  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault()
  }, [])

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    const files = Array.from(e.dataTransfer.files)
    const imageFile = files.find(file => file.type.startsWith('image/'))
    
    if (imageFile) {
      setSelectedFile(imageFile)
    } else {
      toast.error('请上传图片文件 (PNG, JPG, JPEG)')
    }
  }, [])

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      setSelectedFile(file)
    }
  }

  // 上传文件
  const handleUpload = async () => {
    if (!selectedFile) return

    setIsUploading(true)
    updateStepStatus('upload', 'running')

    try {
      const floorPlan = await api.floor.upload(selectedFile)
      setUploadedFloor(floorPlan)
      updateStepStatus('upload', 'completed')
      toast.success('文件上传成功！')
      
      // 自动开始分割
      await handleSegment(floorPlan.fileId)
      
    } catch (error: any) {
      console.error('上传失败:', error)
      updateStepStatus('upload', 'failed')
      toast.error(error.response?.data?.detail || '上传失败')
    } finally {
      setIsUploading(false)
    }
  }

  // 开始分割
  const handleSegment = async (fileId: string) => {
    setIsProcessing(true)
    updateStepStatus('segment', 'running')
    
    // 显示处理提示
    toast.info('🤖 AI正在分析您的平面图，这可能需要2-5分钟，请耐心等待...', {
      duration: 10000,
    })

    try {
      const result = await api.floor.segment(fileId)
      
      // 检查是否是任务队列模式
      if ('task_id' in result) {
        setCurrentTask({ 
          task_id: result.task_id, 
          status: 'running', 
          progress: 0,
          created_at: Date.now()
        })
        
        // 轮询任务状态
        pollTaskStatus(result.task_id)
      } else {
        // 直接返回结果
        setSegmentResult(result as SegmentResult)
        updateStepStatus('segment', 'completed')
        toast.success('分割完成！')
        
        // 自动开始矢量化
        await handleVectorize(fileId, result as SegmentResult)
      }
      
    } catch (error: any) {
      console.error('分割失败:', error)
      updateStepStatus('segment', 'failed')
      
      // 使用增强的错误消息
      const errorMessage = error.userMessage || 
                          error.response?.data?.detail || 
                          (error.code === 'ECONNABORTED' ? 'AI处理超时，请稍后重试' : '分割失败')
      
      // 检查是否是超时错误，提供重试选项
      if (error.code === 'ECONNABORTED' || error.message?.includes('timeout')) {
        const currentRetry = retryCount['segment'] || 0
        if (currentRetry < 2) { // 最多重试2次
          toast.error(`${errorMessage} (第${currentRetry + 1}次重试)`, {
            action: {
              label: '重试',
              onClick: () => {
                setRetryCount(prev => ({ ...prev, segment: currentRetry + 1 }))
                handleSegment(fileId)
              }
            }
          })
        } else {
          toast.error('多次重试失败，请检查网络连接或稍后再试')
        }
      } else {
        toast.error(errorMessage)
      }
      
      setIsProcessing(false)
    }
  }

  // 开始矢量化
  const handleVectorize = async (fileId: string, segmentResult: SegmentResult) => {
    updateStepStatus('vectorize', 'running')

    try {
      const vectorizeResult = await api.floor.vectorize(segmentResult, fileId)
      
      updateStepStatus('vectorize', 'completed')
      toast.success('矢量化完成！')
      
      // 根据选择的建模方法调用相应的函数
      switch (modelingMethod) {
        case 'mcp':
          await handleMCPModeling(vectorizeResult.vectorId)
          break
        case 'hybrid':
          await handleHybrid3D(vectorizeResult.vectorId)
          break
        case 'traditional':
          await handleFallbackReconstruct(vectorizeResult.vectorId)
          break
        default:
          await handleHybrid3D(vectorizeResult.vectorId)
      }
      
    } catch (error: any) {
      console.error('矢量化失败:', error)
      updateStepStatus('vectorize', 'failed')
      
      const errorMessage = error.userMessage || 
                          error.response?.data?.detail || 
                          (error.code === 'ECONNABORTED' ? '矢量化处理超时，请稍后重试' : '矢量化失败')
      
      toast.error(errorMessage)
    }
  }

  // 开始混合3D建模
  const handleHybrid3D = async (vectorId: string) => {
    updateStepStatus('hybrid_3d', 'running')
    toast.info('🏗️ 正在生成Web演示和专业3D模型，预计需要1-2分钟...')

    try {
      // 调用混合3D建模API
      const response = await fetch(`${AI_BASE}/ai/3d/test-hybrid`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const hybridResult = await response.json()
      
      if (hybridResult.status === 'success') {
        updateStepStatus('hybrid_3d', 'completed')
        updateStepStatus('complete', 'completed')
        
        // 保存混合3D建模结果
        setHybrid3dResult(hybridResult)
        
        // 构建Web演示URL
        const demoUrl = `${AI_BASE}/${hybridResult.web_demo}`
        setWebDemoUrl(demoUrl)
        
        toast.success(`🎉 混合3D建模完成！生成了${hybridResult.formats?.length || 0}种格式`)
        console.log('混合3D建模结果:', hybridResult)
        
      } else {
        throw new Error(hybridResult.message || '混合3D建模失败')
      }
      
    } catch (error: any) {
      console.error('混合3D建模失败:', error)
      updateStepStatus('hybrid_3d', 'failed')
      updateStepStatus('complete', 'failed')
      
      const errorMessage = error.message || '混合3D建模失败，请稍后重试'
      toast.error(errorMessage)
      
      // 回退到传统3D重建
      toast.info('正在尝试传统3D重建...')
      await handleFallbackReconstruct(vectorId)
    }
  }

  // 传统3D重建（备用方案）
  const handleFallbackReconstruct = async (vectorId: string) => {
    try {
      const reconstructResult = await api.reconstruction.reconstruct(vectorId, 'hospital_standard')
      
      updateStepStatus('complete', 'completed')
      toast.success('传统3D重建完成！')
      
      // 保存3D模型URL供下载使用
      setGlbUrl(reconstructResult.glbUrl)
      console.log('3D模型URL:', reconstructResult.glbUrl)
      
    } catch (error: any) {
      console.error('传统3D重建也失败:', error)
      updateStepStatus('complete', 'failed')
      
      const errorMessage = error.userMessage || 
                          error.response?.data?.detail || 
                          (error.code === 'ECONNABORTED' ? '3D重建处理超时，请稍后重试' : '3D重建失败')
      
      toast.error(errorMessage)
    }
  }

  // MCP AI建模
  const handleMCPModeling = async (vectorId: string) => {
    updateStepStatus('hybrid_3d', 'running')
    toast.info('🤖 正在启动AI建模引擎，预计需要2-3分钟...')
    
    try {
      const response = await fetch(`${AI_BASE}/ai/3d/test-mcp`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const mcpResult = await response.json()
      
      if (mcpResult.status === 'success') {
        updateStepStatus('hybrid_3d', 'completed')
        updateStepStatus('complete', 'completed')
        
        // 保存MCP建模结果
        setHybrid3dResult({
          ...mcpResult,
          modeling_type: 'MCP AI',
          web_files: 1,
          professional_files: 1,
          formats: ['glb']
        })
        
        // 设置模型URL
        if (mcpResult.model_path) {
          const modelUrl = `${AI_BASE}/${mcpResult.model_path.replace(/\\/g, '/')}`
          setGlbUrl(modelUrl)
        }
        
        toast.success(`🎉 AI建模完成！使用${mcpResult.modeling_approach}`)
        console.log('MCP建模结果:', mcpResult)
        
      } else {
        throw new Error(mcpResult.message || 'MCP建模失败')
      }
      
    } catch (error: any) {
      console.error('MCP建模失败:', error)
      updateStepStatus('hybrid_3d', 'failed')
      updateStepStatus('complete', 'failed')
      
      const errorMessage = error.message || 'MCP建模失败，请稍后重试'
      toast.error(errorMessage)
      
      // 回退到混合建模
      toast.info('正在尝试混合建模方案...')
      await handleHybrid3D(vectorId)
    }
  }

  // 轮询任务状态
  const pollTaskStatus = async (taskId: string) => {
    const pollInterval = setInterval(async () => {
      try {
        const taskStatus = await api.tasks.getTaskStatus(taskId)
        setCurrentTask(taskStatus)

        if (taskStatus.status === 'completed') {
          clearInterval(pollInterval)
          setSegmentResult(taskStatus.result)
          updateStepStatus('segment', 'completed')
          setIsProcessing(false)
          toast.success('分割完成！')
          
          // 继续执行矢量化
          const fileId = uploadedFloor?.fileId
          if (fileId) {
            await handleVectorize(fileId, taskStatus.result)
          }
        } else if (taskStatus.status === 'failed') {
          clearInterval(pollInterval)
          updateStepStatus('segment', 'failed')
          setIsProcessing(false)
          toast.error(taskStatus.error || '处理失败')
        }
      } catch (error) {
        console.error('获取任务状态失败:', error)
      }
    }, 2000) // 每2秒轮询一次

    // 30秒后停止轮询
    setTimeout(() => clearInterval(pollInterval), 30000)
  }

  const updateStepStatus = (stepId: string, status: ProcessingStep['status']) => {
    setSteps(prev => prev.map(step => 
      step.id === stepId ? { ...step, status } : step
    ))
  }

  const getStepIcon = (step: ProcessingStep) => {
    if (step.status === 'running') return <IconLoader size={20} className="animate-spin" />
    if (step.status === 'completed') return <IconCheck size={20} />
    if (step.status === 'failed') return <IconX size={20} />
    return step.icon
  }

  const getStepColor = (status: ProcessingStep['status']) => {
    switch (status) {
      case 'running': return 'text-blue-600 bg-blue-50'
      case 'completed': return 'text-green-600 bg-green-50'
      case 'failed': return 'text-red-600 bg-red-50'
      default: return 'text-gray-600 bg-gray-50'
    }
  }

  const resetProcessing = () => {
    setSelectedFile(null)
    setUploadedFloor(null)
    setSegmentResult(null)
    setCurrentTask(null)
    setIsUploading(false)
    setIsProcessing(false)
    setGlbUrl(null)
    setHybrid3dResult(null)
    setWebDemoUrl(null)
    setRetryCount({})
    setSteps(prev => prev.map(step => ({ ...step, status: 'pending' })))
  }

  return (
    <AuthGuard>
      <div className="min-h-screen bg-gray-50 p-6">
      <div className="max-w-6xl mx-auto space-y-6">
        {/* 页面标题 */}
        <div className="flex items-center space-x-2 text-sm text-gray-500 mb-4">
          <span>医疗数字孪生</span>
          <IconChevronRight size={16} />
          <span className="text-blue-600">平面图处理</span>
        </div>

        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">平面图AI处理工作台</h1>
            <p className="text-gray-600 mt-1">上传医院平面图，AI自动分割识别房间、门窗等结构</p>
          </div>
          {segmentResult && (
            <Button onClick={resetProcessing} variant="outline">
              🔄 重新开始
            </Button>
          )}
        </div>

        {/* 建模方法选择 */}
        <Card>
          <CardHeader>
            <CardTitle>🛠️ 建模方法选择</CardTitle>
            <CardDescription>选择适合您需求的3D建模方式</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div
                className={`p-4 border rounded-lg cursor-pointer transition-all ${
                  modelingMethod === 'mcp' 
                    ? 'border-blue-500 bg-blue-50 shadow-md' 
                    : 'border-gray-200 hover:border-gray-300'
                }`}
                onClick={() => setModelingMethod('mcp')}
              >
                <div className="flex items-center space-x-2 mb-2">
                  <span className="text-2xl">🤖</span>
                  <h3 className="font-semibold">MCP AI建模</h3>
                  <Badge variant="secondary" className="bg-purple-100 text-purple-700">新功能</Badge>
                </div>
                <p className="text-sm text-gray-600">
                  使用Blender-MCP AI驱动的智能建模，自动生成高质量医院3D模型
                </p>
                <div className="mt-2 text-xs text-gray-500">
                  ⚡ AI驱动 • 🎨 高质量 • 🔧 自动优化
                </div>
              </div>

              <div
                className={`p-4 border rounded-lg cursor-pointer transition-all ${
                  modelingMethod === 'hybrid' 
                    ? 'border-blue-500 bg-blue-50 shadow-md' 
                    : 'border-gray-200 hover:border-gray-300'
                }`}
                onClick={() => setModelingMethod('hybrid')}
              >
                <div className="flex items-center space-x-2 mb-2">
                  <span className="text-2xl">🌐</span>
                  <h3 className="font-semibold">混合建模</h3>
                  <Badge variant="outline" className="bg-green-100 text-green-700">推荐</Badge>
                </div>
                <p className="text-sm text-gray-600">
                  Web演示(高德地图+Three.js) + 专业模型(FreeCAD/Blender)，适合多场景使用
                </p>
                <div className="mt-2 text-xs text-gray-500">
                  🌍 Web友好 • 💼 专业级 • 📱 多平台
                </div>
              </div>

              <div
                className={`p-4 border rounded-lg cursor-pointer transition-all ${
                  modelingMethod === 'traditional' 
                    ? 'border-blue-500 bg-blue-50 shadow-md' 
                    : 'border-gray-200 hover:border-gray-300'
                }`}
                onClick={() => setModelingMethod('traditional')}
              >
                <div className="flex items-center space-x-2 mb-2">
                  <span className="text-2xl">🏗️</span>
                  <h3 className="font-semibold">传统建模</h3>
                  <Badge variant="outline">稳定</Badge>
                </div>
                <p className="text-sm text-gray-600">
                  使用传统Blender脚本生成基础3D模型，兼容性好，速度快
                </p>
                <div className="mt-2 text-xs text-gray-500">
                  ⚡ 快速 • 🔒 稳定 • 📦 轻量
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 处理流程 */}
        <Card>
          <CardHeader>
            <CardTitle>处理流程</CardTitle>
            <CardDescription>AI处理进度跟踪</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              {steps.map((step, index) => (
                <div key={step.id} className="flex items-center">
                  <div className={`flex items-center space-x-2 px-3 py-2 rounded-lg ${getStepColor(step.status)}`}>
                    {getStepIcon(step)}
                    <span className="text-sm font-medium">{step.name}</span>
                  </div>
                  {index < steps.length - 1 && (
                    <IconChevronRight size={16} className="mx-3 text-gray-400" />
                  )}
                </div>
              ))}
            </div>
            
            {/* 任务进度 */}
            {(currentTask || isProcessing) && (
              <div className="mt-4 space-y-3">
                <div className="flex justify-between text-sm">
                  <span>处理进度</span>
                  <span>{currentTask ? Math.round(currentTask.progress * 100) : 0}%</span>
                </div>
                <Progress value={currentTask ? currentTask.progress * 100 : 0} className="h-2" />
                
                {/* 处理状态说明 */}
                <div className="text-sm text-gray-600">
                  {isProcessing && !currentTask && (
                    <div className="flex items-center space-x-2">
                      <IconLoader size={16} className="animate-spin" />
                      <span>🤖 AI正在处理您的平面图，请稍候...</span>
                    </div>
                  )}
                  {currentTask && (
                    <div>任务ID: {currentTask.task_id}</div>
                  )}
                </div>
                {currentTask?.eta && (
                  <p className="text-xs text-gray-500">
                    预计剩余时间: {Math.round(currentTask.eta)} 秒
                  </p>
                )}
              </div>
            )}
          </CardContent>
        </Card>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* 左侧 - 上传区域 */}
          <Card>
            <CardHeader>
              <CardTitle>文件上传</CardTitle>
              <CardDescription>支持 PNG、JPG、JPEG 格式，最大 100MB</CardDescription>
            </CardHeader>
            <CardContent>
              {!selectedFile ? (
                <div
                  className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-400 transition-colors cursor-pointer"
                  onDragOver={handleDragOver}
                  onDrop={handleDrop}
                  onClick={() => document.getElementById('file-input')?.click()}
                >
                  <IconUpload size={48} className="mx-auto text-gray-400 mb-4" />
                  <p className="text-lg font-medium text-gray-700 mb-2">
                    拖拽平面图文件到这里
                  </p>
                  <p className="text-gray-500 mb-4">或点击选择文件</p>
                  <input
                    id="file-input"
                    type="file"
                    accept="image/*"
                    onChange={handleFileSelect}
                    className="hidden"
                  />
                  <Button>选择文件</Button>
                </div>
              ) : (
                <div className="space-y-4">
                  <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                    <div className="flex items-center space-x-3">
                      <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                        <IconFileText size={20} className="text-blue-600" />
                      </div>
                      <div>
                        <p className="font-medium">{selectedFile.name}</p>
                        <p className="text-sm text-gray-500">
                          {(selectedFile.size / 1024 / 1024).toFixed(2)} MB
                        </p>
                      </div>
                    </div>
                    <Button
                      onClick={() => setSelectedFile(null)}
                      variant="ghost"
                      size="sm"
                    >
                      <IconX size={16} />
                    </Button>
                  </div>

                  {/* 预览图 */}
                  <div className="border rounded-lg p-2">
                    <img
                      src={URL.createObjectURL(selectedFile)}
                      alt="预览"
                      className="w-full h-48 object-contain bg-gray-50 rounded"
                    />
                  </div>

                  <Button
                    onClick={handleUpload}
                    disabled={isUploading || isProcessing}
                    className="w-full"
                  >
                    {isUploading ? (
                      <div className="flex items-center">
                        <IconLoader size={16} className="animate-spin mr-2" />
                        上传中...
                      </div>
                    ) : (
                      '开始上传并处理'
                    )}
                  </Button>
                </div>
              )}
            </CardContent>
          </Card>

          {/* 右侧 - 处理结果 */}
          <Card>
            <CardHeader>
              <CardTitle>处理结果</CardTitle>
              <CardDescription>AI分割识别结果</CardDescription>
            </CardHeader>
            <CardContent>
              {!segmentResult ? (
                <div className="text-center py-12">
                  <IconClock size={48} className="mx-auto text-gray-400 mb-4" />
                  <p className="text-gray-500">等待处理结果...</p>
                </div>
              ) : (
                <Tabs defaultValue="overview" className="w-full">
                  <TabsList className="grid w-full grid-cols-3">
                    <TabsTrigger value="overview">概览</TabsTrigger>
                    <TabsTrigger value="rooms">房间</TabsTrigger>
                    <TabsTrigger value="elements">元素</TabsTrigger>
                  </TabsList>

                  <TabsContent value="overview" className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <div className="bg-blue-50 p-3 rounded-lg">
                        <p className="text-sm text-blue-600">房间数量</p>
                        <p className="text-2xl font-bold text-blue-900">
                          {segmentResult.rooms.length}
                        </p>
                      </div>
                      <div className="bg-green-50 p-3 rounded-lg">
                        <p className="text-sm text-green-600">门窗数量</p>
                        <p className="text-2xl font-bold text-green-900">
                          {segmentResult.doors.length + segmentResult.windows.length}
                        </p>
                      </div>
                    </div>

                    {/* 分割结果预览 */}
                    {segmentResult.maskUrl && (
                      <div className="space-y-2">
                        <p className="font-medium">分割结果预览</p>
                        <div className="border rounded-lg p-2">
                          <img
<<<<<<< HEAD
                            src={`${process.env.NEXT_PUBLIC_AI_API_BASE_URL || 'http://localhost:8000'}${segmentResult.maskUrl}`}
=======
                            src={`${AI_BASE}${segmentResult.maskUrl}`}
>>>>>>> 2b1414599d9e635ed6f7f739f5d192143c8f58df
                            alt="分割结果"
                            className="w-full h-48 object-contain bg-gray-50 rounded"
                          />
                        </div>
                        <div className="flex space-x-2">
                          <Button size="sm" variant="outline">
                            <IconEye size={16} className="mr-1" />
                            查看详情
                          </Button>
                          <Button size="sm" variant="outline">
                            <IconDownload size={16} className="mr-1" />
                            下载结果
                          </Button>
                          <Button 
                            size="sm" 
                            onClick={() => {
                              if (uploadedFloor?.fileId) {
                                handleVectorize(uploadedFloor.fileId, segmentResult)
                              }
                            }}
                            disabled={isProcessing}
                          >
                            {isProcessing ? <IconLoader size={16} className="animate-spin mr-1" /> : <IconFileText size={16} className="mr-1" />}
                            继续处理
                          </Button>
                        </div>
                      </div>
                    )}
                  </TabsContent>

                  <TabsContent value="rooms" className="space-y-3">
                    {segmentResult.rooms.map((room, index) => (
                      <div key={room.id} className="flex items-center justify-between p-3 border rounded-lg">
                        <div>
                          <p className="font-medium">{room.label}</p>
                          <p className="text-sm text-gray-500">
                            面积: {room.area?.toFixed(0)} 像素²
                          </p>
                        </div>
                        <Badge variant="secondary">
                          {(room.confidence * 100).toFixed(1)}%
                        </Badge>
                      </div>
                    ))}
                  </TabsContent>

                  <TabsContent value="elements" className="space-y-3">
                    {[...segmentResult.doors, ...segmentResult.windows].map((element, index) => (
                      <div key={element.id} className="flex items-center justify-between p-3 border rounded-lg">
                        <div>
                          <p className="font-medium">
                            {element.type === 'door' ? '🚪 门' : '🪟 窗'}
                          </p>
                          <p className="text-sm text-gray-500">ID: {element.id}</p>
                        </div>
                        <Badge variant="secondary">
                          {(element.confidence * 100).toFixed(1)}%
                        </Badge>
                      </div>
                    ))}
                  </TabsContent>
                </Tabs>
              )}
            </CardContent>
          </Card>

          {/* 完成状态显示 */}
          {steps.find(s => s.id === 'complete')?.status === 'completed' && (
            <Card className="mt-6">
              <CardHeader>
                <CardTitle className="text-green-600">
                  🎉 {
                    modelingMethod === 'mcp' ? 'MCP AI建模完成' :
                    modelingMethod === 'hybrid' ? '混合3D建模完成' :
                    '传统3D建模完成'
                  }
                </CardTitle>
                <CardDescription>
                  {
                    modelingMethod === 'mcp' ? 
                      '已使用AI驱动的Blender建模技术成功生成高质量3D模型' :
                    modelingMethod === 'hybrid' ? 
                      '已成功生成Web演示和专业3D模型，支持多种格式和交互体验' :
                      '已使用传统Blender脚本成功生成基础3D模型'
                  }
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-6">
                  {/* 处理步骤概览 */}
                  <div className="grid grid-cols-4 gap-4">
                    <div className="text-center p-4 bg-green-50 rounded-lg">
                      <div className="text-2xl font-bold text-green-600">✅</div>
                      <div className="text-sm text-green-700">AI分割完成</div>
                    </div>
                    <div className="text-center p-4 bg-blue-50 rounded-lg">
                      <div className="text-2xl font-bold text-blue-600">🗺️</div>
                      <div className="text-sm text-blue-700">矢量化完成</div>
                    </div>
                    <div className="text-center p-4 bg-purple-50 rounded-lg">
                      <div className="text-2xl font-bold text-purple-600">
                        {modelingMethod === 'mcp' ? '🤖' : modelingMethod === 'hybrid' ? '🏗️' : '🔧'}
                      </div>
                      <div className="text-sm text-purple-700">
                        {modelingMethod === 'mcp' ? 'MCP AI建模' : modelingMethod === 'hybrid' ? '混合3D建模' : '传统建模'}
                      </div>
                    </div>
                    <div className="text-center p-4 bg-yellow-50 rounded-lg">
                      <div className="text-2xl font-bold text-yellow-600">🎉</div>
                      <div className="text-sm text-yellow-700">处理完成</div>
                    </div>
                  </div>
                  
                  {/* 混合3D建模结果展示 */}
                  {hybrid3dResult && (
                    <div className="space-y-4">
                      <h4 className="font-semibold text-lg">🎯 建模结果</h4>
                      
                      {/* 统计信息 */}
                      <div className="grid grid-cols-3 gap-4 text-center">
                        <div className="p-3 bg-gradient-to-r from-blue-50 to-cyan-50 rounded-lg border">
                          <div className="text-xl font-bold text-blue-600">{hybrid3dResult.web_files || 0}</div>
                          <div className="text-sm text-blue-700">Web文件</div>
                        </div>
                        <div className="p-3 bg-gradient-to-r from-green-50 to-emerald-50 rounded-lg border">
                          <div className="text-xl font-bold text-green-600">{hybrid3dResult.professional_files || 0}</div>
                          <div className="text-sm text-green-700">专业模型</div>
                        </div>
                        <div className="p-3 bg-gradient-to-r from-purple-50 to-violet-50 rounded-lg border">
                          <div className="text-xl font-bold text-purple-600">{hybrid3dResult.formats?.length || 0}</div>
                          <div className="text-sm text-purple-700">格式类型</div>
                        </div>
                      </div>

                      {/* 支持的格式 */}
                      {hybrid3dResult.formats && hybrid3dResult.formats.length > 0 && (
                        <div>
                          <h5 className="font-medium mb-2">📄 支持格式</h5>
                          <div className="flex flex-wrap gap-2">
                            {hybrid3dResult.formats.map((format: string, index: number) => (
                              <Badge key={index} variant="outline" className="uppercase">
                                {format}
                              </Badge>
                            ))}
                          </div>
                        </div>
                      )}
                    </div>
                  )}
                  
                  {/* 操作按钮 */}
                  <div className="space-y-3">
                    {/* Web演示按钮 */}
                    {webDemoUrl && (
                      <Button 
                        onClick={() => window.open(webDemoUrl, '_blank')}
                        className="w-full bg-gradient-to-r from-blue-500 to-cyan-500 hover:from-blue-600 hover:to-cyan-600"
                        size="lg"
                      >
                        <IconEye size={20} className="mr-2" />
                        🌐 打开Web 3D演示 (高德地图+Three.js)
                      </Button>
                    )}

                    <div className="grid grid-cols-2 gap-3">
                      {/* 下载专业模型 */}
                    <Button 
                      onClick={() => {
                          if (hybrid3dResult?.output_dir) {
                            toast.info('专业模型文件已生成，请查看服务器目录：' + hybrid3dResult.output_dir)
                          } else if (glbUrl) {
<<<<<<< HEAD
                          window.open(`${process.env.NEXT_PUBLIC_AI_API_BASE_URL || 'http://localhost:8000'}${glbUrl}`, '_blank')
=======
                          window.open(`${AI_BASE}${glbUrl}`, '_blank')
>>>>>>> 2b1414599d9e635ed6f7f739f5d192143c8f58df
                        }
                      }}
                        variant="outline"
                        disabled={!hybrid3dResult && !glbUrl}
                    >
                      <IconDownload size={16} className="mr-2" />
                        专业模型
                    </Button>

                      {/* 重新开始 */}
                    <Button 
                      variant="outline"
                        onClick={resetProcessing}
                    >
                        🔄 重新开始
                    </Button>
                    </div>

                    {/* 输出目录信息 */}
                    {hybrid3dResult?.output_dir && (
                      <div className="p-3 bg-gray-50 rounded-lg text-sm">
                        <strong>📁 输出目录:</strong> {hybrid3dResult.output_dir}
                        <br />
                        <span className="text-gray-600">包含Web演示、专业模型、文档和部署脚本</span>
                      </div>
                    )}
                  </div>
                </div>
              </CardContent>
            </Card>
          )}
        </div>
        </div>
      </div>
    </AuthGuard>
  )
} 